import subprocess,re,multiprocessing,time,os,pymysql,time
from multiprocessing import Pool
#扫描ip网段port端口open的主机
def nmap80(ip,port,tenIPlist):
	ip = str(ip)
	port=str(port)
	#检测IP格式,格式不对结束脚本
	p= re.compile('^(\d)+\.(\d)+\.(\d)+\.(\d)+(//\d｛1,2｝){0,1}')
	if p.match(ip):
		port80 = os.popen('/usr/bin/nmap --unprivileged  --open -sT -p %s %s'  % (port,ip)).read()
		hostList = re.findall(r"[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+", port80)
	else:

		hostList= []
	mycallback([port]+hostList,tenIPlist)


def readDB(DBname):
	db = pymysql.connect("113.215.1.161", "root", "root", "mydb", charset="utf8")  # 打开数据库连接
	cursor = db.cursor()  # 使用cursor()方法获取操作游标
	sql = "SELECT * FROM %s" % DBname
	cursor.execute(sql)
	results = cursor.fetchall()
	db.close()
	return results


def mycallback(IPlist,tenIPlist):

	port=IPlist[0]
	IPlist.pop(0)
	for x in IPlist:
		x = x.strip()
		if x not in tenIPlist:
			print(x)
			updateDB([x,port])
			with open('/var/www/html/log/scanlog.txt', 'a+') as f:
				f.writelines(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+"\tIP:\t%s\t端口\t%s\n" % (x,port))




def updateDB(IP):#[host,port]

	db=pymysql.connect("113.215.1.161","root","root","mydb",charset="utf8" )# 打开数据库连接
	cursor = db.cursor()# 使用cursor()方法获取操作游标
	#查询
	sqlFind='SELECT * FROM ten_oc WHERE host="%s"' % IP[0]
	#更新
	sqlupdate='UPDATE ten_oc SET mon="yes",port="%s" WHERE host="%s" ' % (IP[1],IP[0])
	#插入
	sqlInsert='INSERT INTO ten_oc(host,mon,port) VALUES ("%s","yes","%s")' % tuple(IP)
	print(sqlFind)
	Find=cursor.execute(sqlFind)
	print("找到%s条记录" % Find)
	if Find==0:#如果库中无次记录
		try:
			cursor.execute(sqlInsert)  # 插入记录
			print(sqlInsert,"成功")
		except:
			print(sqlInsert,"失败")
			db.close()
			return 0
	else:
		try:
			cursor.execute(sqlupdate)#更新记录
			print(sqlupdate,"成功")
		except:
			print(sqlupdate, "失败")
			db.close()
			return 0
	db.close()


def go(port,tenIPlist):

	#ip=input("输入要扫描的网段：")
	ip=['113.215.3.64/26','113.215.11.0/25','113.215.11.128/25','113.215.13.128/26','113.215.22.128/26']
	#port=input("输入要扫描的端口(缺省80)：")
	#如果端口输入格式不对默认改为80端口

	print("正在扫描tcp/%s端口……" % port)
	print("端口：",port)
	for i in ip:
		nmap80(i,port,tenIPlist)


def main():
	tenIPlist = []
	ten_OC = readDB("ten_oc")
	for x in ten_OC:
		if x[3] =="yes":
			ip = x[0].strip()
			tenIPlist.append(ip)
	print(tenIPlist)
	port = ["8080","443", "80"]
	for i in port:
		go(i,tenIPlist)

if __name__ == '__main__':
	main()
